<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\UserRequest;
use App\User;
use DB;
use Hash;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function login()
    {
        return view('login');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function relog()
    {
        return view('relog');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function dorelog(UserRequest $request)
    {
        $user = new User;
        $user -> username = $request -> username;
        $user -> password = Hash::make($request -> password);
        $user -> email = $request -> email;
        //图片上传
        if($request->hasFile('img')){
            $filename = time().rand(10000,90000);
            $suffix = $request->file('img')->getClientOriginalExtension(); 
            $dirname = './uploads/';
            $file = $filename.'.'.$suffix;
            $request -> file('img') -> move($dirname,$file);
            $user -> img = $dirname.$file;
        }
        if($user->save()){
            return redirect('/login');
        }else{
            return back();
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function dologin(Request $request)
    {
        $username = $request->username;

        //读取数据库
        $user = User::where('username',$username)->first();

        //判断
        if(empty($user)) {
            return back();
        }

        //检测密码
        if(Hash::check($request->password, $user->password)) {
            //写入session
            session(['id' => $user->id]);

            return redirect('/shou');
        }else{
            return back();
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function shou()
    {
        return view('shou');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        $request->session()->flush();
        return redirect('/login');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function tupian()
    {
        $imgs = User::paginate(3);
        return view('tupian',['img'=>$imgs]);
    }
}
